class ImageLoader {
  constructor(imgs) {
    this.imgs = imgs
    this.size = imgs.length
    this.now = 0
    this.loadingProcess = 0
    this.img = new Image()
    this.onComple = () => {}
    this.onProcess = () => {}
  }
  addSource(item) {
    this.imgs.push(item)
    this.size = this.imgs.length
  }
  addCompletionListener(fn) {
    if (typeof fn === 'function') {
      this.onComple = fn
    }
  }
  addProcessListener(fn) {
    if (typeof fn === 'function') {
      this.onProcess = fn
    }
  }
  loop() {
    this.now++
    this.loadingProcess = parseInt((this.now / this.size) * 100)
    if (this.now < this.size) {
      this.onProcess(this.loadingProcess)
      this.start()
    } else {
      this.onProcess(this.loadingProcess)
      this.onComple()
    }
  }
  start() {
    if (this.size === 0) {
      console.log('没有要加载的图片')
      return
    }

    if (this.size === this.now) {
      console.log('都加载好了')
      return
    }

    this.img.onload = () => {
      this.img.onload = null
      this.loop()
    }

    this.img.src = this.imgs[this.now]
  }
}
